package com.zdb.demo.flink.streaming;

import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.io.InputFormat;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.io.PojoCsvInputFormat;
import org.apache.flink.api.java.io.PrintingOutputFormat;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple1;
import org.apache.flink.api.java.typeutils.PojoTypeInfo;
import org.apache.flink.api.java.typeutils.TypeExtractor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.core.fs.FileInputSplit;
import org.apache.flink.core.fs.Path;
import org.apache.flink.queryablestate.client.state.ImmutableValueState;
import org.apache.flink.runtime.state.memory.MemoryStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 实现三个 Flink Stream Job，分别达到如下效果，并截图
 * 造成 HIGH 背压，并且导致 Checkpoint 失败
 * 引起 LOW 背压，并且 Checkpoint 耗时长
 * 无背压，并且 Checkpoint 正常
 */
public class H10 {

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration(){{
            setInteger("rest.port", 9191);
            setBoolean("local.start-webserver", true);
        }};
        StreamExecutionEnvironment streamEnv = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
        streamEnv.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
//        streamEnv.enableCheckpointing(2000, CheckpointingMode.AT_LEAST_ONCE);
//        streamEnv.setStateBackend(new MemoryStateBackend());
        hotestItem(streamEnv);
        streamEnv.execute();
    }

    private static void hotestItem(StreamExecutionEnvironment streamEnv) {

        PojoTypeInfo<UserBehavior> userBehaviorPojoType = (PojoTypeInfo<UserBehavior>) TypeExtractor.createTypeInfo(UserBehavior.class);
        String[] fields = new String[]{"userId", "itemId", "categoryId", "behavior", "timestamp"};
        Path data = new Path("file:/E:/downloads/UserBehavior.csv");
        InputFormat<UserBehavior, FileInputSplit> inputFormat = new PojoCsvInputFormat<>(data, userBehaviorPojoType, fields);
        DataStream<UserBehavior> dataSource = streamEnv.createInput(inputFormat, Types.POJO(UserBehavior.class));
        dataSource.assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<UserBehavior>(Time.minutes(5)) {
            @Override
            public long extractTimestamp(UserBehavior element) {
                return element.timestamp * 1000;
            }
        }).filter((UserBehavior userBehavior) -> "buy".equalsIgnoreCase(userBehavior.behavior))
                .keyBy("itemId")
                .timeWindow(Time.hours(1), Time.minutes(15))
                .aggregate(new AggregateFunction<UserBehavior, Long, Long>() {
                    @Override
                    public Long createAccumulator() {
                        return 0L;
                    }

                    @Override
                    public Long add(UserBehavior value, Long accumulator) {
                        return accumulator + 1;
                    }

                    @Override
                    public Long getResult(Long accumulator) {
                        return accumulator;
                    }

                    @Override
                    public Long merge(Long a, Long b) {
                        return a + b;
                    }
                }, new WindowFunction<Long, ItemPurchase, Tuple, TimeWindow>() {
                    @Override
                    public void apply(Tuple tuple, TimeWindow window, Iterable<Long> input, Collector<ItemPurchase> out) throws Exception {
                        input.forEach(value -> {
                            String itemId = ((Tuple1<String>)tuple).f0;
                            long amount = value;
                            out.collect(new ItemPurchase(window.getStart(), window.getEnd(), itemId, amount));
                        });
                    }
                })
                .keyBy("end")
                .process(new KeyedProcessFunction<Tuple, ItemPurchase, ItemPurchase>() {

                    private int topN = 5;
                    private int cacheSize = 100;
                    private ListState<ItemPurchase> itemPurchaseListState;
                    private ValueState<Integer> cacheSizeState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ListStateDescriptor<ItemPurchase> desc = new ListStateDescriptor<ItemPurchase>(
                                "itemPurchaseState", ItemPurchase.class);
                        ValueStateDescriptor<Integer> cacheSizeDesc = new ValueStateDescriptor<Integer>("valueState", Integer.class);
                        itemPurchaseListState = getRuntimeContext().getListState(desc);
                        cacheSizeState = getRuntimeContext().getState(cacheSizeDesc);
                    }

                    @Override
                    public void processElement(ItemPurchase value, Context ctx, Collector<ItemPurchase> out) throws Exception {
                        // 如果达到缓存大小则压缩到topN个
                        Integer cnt = cacheSizeState.value();
                        if(cnt != null && cnt >= cacheSize) {
                            // 压缩
                            List<ItemPurchase> list = topN(itemPurchaseListState, topN);
                            itemPurchaseListState.clear();
                            list.add(value);
                            itemPurchaseListState.addAll(list);
                            cacheSizeState.update(list.size());
                        } else {
                            itemPurchaseListState.add(value);
                            cacheSizeState.update(cnt == null ? 1 : cnt + 1);
                        }
                        ctx.timerService().registerEventTimeTimer(value.end + 1);
                    }

                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<ItemPurchase> out) throws Exception {
                        // 获取所有的商品点击量
                        List<ItemPurchase> itemPurchases = topN(itemPurchaseListState, topN);
                        itemPurchases.forEach((ItemPurchase itemPurchase) -> out.collect(itemPurchase));
                    }
                }).writeUsingOutputFormat(new PrintingOutputFormat<>());

    }

    private static List<ItemPurchase> topN(ListState<ItemPurchase> itemPurchaseListState, int topN) throws Exception {
        List<ItemPurchase> list = new ArrayList<>();
        for(ItemPurchase ip : itemPurchaseListState.get()) {
            list.add(ip);
        }
        list.sort(new Comparator<ItemPurchase>() {
            @Override
            public int compare(ItemPurchase o1, ItemPurchase o2) {
                long c = o2.amount - o1.amount;
                if(c > 0) {
                    return 1;
                } else if(c == 0) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });
        return list.subList(0, Math.min(topN, list.size()));
    }

    public static class UserBehavior {
        String userId;
        String itemId;
        String categoryId;
        String behavior;
        long timestamp;

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public String getItemId() {
            return itemId;
        }

        public void setItemId(String itemId) {
            this.itemId = itemId;
        }

        public String getCategoryId() {
            return categoryId;
        }

        public void setCategoryId(String categoryId) {
            this.categoryId = categoryId;
        }

        public String getBehavior() {
            return behavior;
        }

        public void setBehavior(String behavior) {
            this.behavior = behavior;
        }

        public long getTimestamp() {
            return timestamp;
        }

        public void setTimestamp(long timestamp) {
            this.timestamp = timestamp;
        }
    }

    public static class ItemPurchase {
        long start;
        long end;
        String itemId;
        long amount;

        public ItemPurchase() {
        }

        public ItemPurchase(long start, long end, String itemId, long amount) {
            this.start = start;
            this.end = end;
            this.itemId = itemId;
            this.amount = amount;
        }

        public long getStart() {
            return start;
        }

        public void setStart(long start) {
            this.start = start;
        }

        public long getEnd() {
            return end;
        }

        public void setEnd(long end) {
            this.end = end;
        }

        public String getItemId() {
            return itemId;
        }

        public void setItemId(String itemId) {
            this.itemId = itemId;
        }

        public long getAmount() {
            return amount;
        }

        public void setAmount(long amount) {
            this.amount = amount;
        }

        @Override
        public String toString() {
            return "ItemPurchase{" +
                    "start=" + start +
                    ", end=" + end +
                    ", itemId='" + itemId + '\'' +
                    ", amount=" + amount +
                    '}';
        }
    }
}



